package dmxGroupControl.transmitters;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;

import artnet4j.*;
import artnet4j.packets.ArtDmxPacket;
import dmxGroupControl.StatusCode;

public class ArtNetTransmitter extends DMXTransmitter
{
	private int sequenceID;
	private InetAddress address;
	private ArtNetServer server;
	int universeID;
	
	public ArtNetTransmitter(String address, int universeID)
	{
		sequenceID = 0;

		server = new ArtNetServer(0, 6454);
		
		this.universeID = universeID;
		try
		{
			this.address = InetAddress.getByName(address);
			server.start();
            UpdateStatus(StatusCode.NOTHING_SENT);
		}
		catch (SocketException | ArtNetException | UnknownHostException e)
		{
            UpdateStatus(e);
			e.printStackTrace();
		}
	}
	
	public void close()
	{
		enabled = false;
	    server.stop();
	}

	public void SendDMXInternal(byte[] data)
	{
	    ArtDmxPacket dmx = new ArtDmxPacket();
        dmx.setUniverse(0, universeID);
        dmx.setSequenceID(sequenceID % 255);
		dmx.setDMX(data, data.length);
		server.unicastPacket(dmx, address);
		sequenceID++;
        if(!AlreadyGreen())
        {
            UpdateStatus(StatusCode.DATA_SENT);
        }
	}
	
	public static String GetLocalAddress()
	{
		try
		{
			return InetAddress.getLocalHost().getHostAddress();
		}
		catch (UnknownHostException e)
		{
			e.printStackTrace();
		}
		return "";
	}

	public int GetID()
	{
	    return universeID;
	}
	
    @Override
    public String GetAddress()
    {
        return address.getHostAddress();
    }

    @Override
    public String GetType()
    {
        return "artnet";
    }
    
    @Override
    public String toString()
    {
        return "ArtNet Transmitter - " + " [" + GetID() + "] " + GetAddress();
    }
}
